package com.ysstech.reportworld.util;


import com.ysstech.common.util.JdbcUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 配置在yml文件中的常量数据
 *
 * @author
 */
@Slf4j
@Configuration
public class DbConnConfig {


    @Value("${input.dbconnconfig.datasource.username}")
    public String inputUsername;
    @Value("${input.dbconnconfig.datasource.password}")
    public String inputPassword;
    @Value("${input.dbconnconfig.datasource.driver-class-name}")
    public String inputDriver;
    @Value("${input.dbconnconfig.datasource.url}")
    public String inputUrl;

    @Value("${output.dbconnconfig.datasource.username}")
    public String outputUsername;
    @Value("${output.dbconnconfig.datasource.password}")
    public String outputPassword;
    @Value("${output.dbconnconfig.datasource.driver-class-name}")
    public String outputDriver;
    @Value("${output.dbconnconfig.datasource.url}")
    public String outputUrl;

    /**
     * 资源库缓存
     */
    private static final Map<String, Connection> DATABASE_REP = new ConcurrentHashMap<>();
    private static final String DBCONNCONFIG_INPUT_DATABASE_CODE = "DBCONNCONFIG_INPUT_DATABASE_CODE";
    private static final String DBCONNCONFIG_OUTPUT_DATABASE_CODE = "DBCONNCONFIG_OUTPUT_DATABASE_CODE";

    /**
     * 获取数据库连接
     *
     * @return
     */
    public Connection getInputConnection() throws Exception {
        // 检查资源库是否存在
       /* if (DATABASE_REP.containsKey(DBCONNCONFIG_INPUT_DATABASE_CODE)) {
            return DATABASE_REP.get(DBCONNCONFIG_INPUT_DATABASE_CODE);
        }*/
        Connection conn = getConnection(inputDriver, inputUrl, inputUsername, inputPassword);
        return conn;
    }

    public Connection getOutputConnection() throws Exception {
        // 检查资源库是否存在
      /*  if (DATABASE_REP.containsKey(DBCONNCONFIG_OUTPUT_DATABASE_CODE)) {
            return DATABASE_REP.get(DBCONNCONFIG_OUTPUT_DATABASE_CODE);
        }*/
        Connection conn = getConnection(outputDriver, outputUrl, outputUsername, outputPassword);
        // DATABASE_REP.put(DBCONNCONFIG_OUTPUT_DATABASE_CODE, conn);
        return conn;
    }

    private Connection getConnection(String driver, String url, String username, String password) throws Exception {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return conn;
    }
}
